import React, { useState, useRef, useEffect, FC } from 'react';
import './index.less';
interface IdentifyingCode {
  onGenerate?: (code: string) => void;
}

const generateCode = () => {
  const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  const len = chars.length;
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += chars[Math.floor(Math.random() * len)];
  }
  return code;
};

const generateLine = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
  ctx.beginPath();
  ctx.moveTo(Math.random() * width, Math.random() * height);
  ctx.lineTo(Math.random() * width, Math.random() * height);
  ctx.strokeStyle = randomColor();
  ctx.stroke();
};

const generateNoise = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
  const noise = 100;
  for (let i = 0; i < noise; i++) {
    ctx.beginPath();
    ctx.arc(Math.random() * width, Math.random() * height, Math.random() * 1, 0, 2 * Math.PI);
    ctx.fillStyle = randomColor();
    ctx.fill();
  }
};

const randomColor = () => {
  return `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.7)`;
};

const IdentifyingCode: React.FC<IdentifyingCode> = (props: IdentifyingCode) => {
  const { onGenerate } = props;
  const [code, setCode] = useState(generateCode());
  const canvasRef = useRef(null);

  const handleClick = () => {
    setCode(generateCode());
  };

  useEffect(() => {
    const canvas: HTMLCanvasElement = canvasRef.current!;
    if (!canvas) {
      return;
    }
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      return;
    }

    const width = canvas.width;
    const height = canvas.height;

    ctx.clearRect(0, 0, width, height);

    // 绘制背景颜色
    ctx.fillStyle = randomColor();
    ctx.fillRect(0, 0, width, height);

    // 绘制code
    ctx.font = 'bold 30px Arial';
    for (let i = 0; i < code.length; i++) {
      ctx.fillStyle = randomColor();
      ctx.save();
      ctx.translate(10 + 20 * i, 30);
      ctx.rotate((Math.random() * Math.PI) / 4 - Math.PI / 8);
      ctx.fillText(code[i], 0, 0);
      ctx.restore();
    }

    for (let i = 0; i < 30; i++) {
      generateLine(ctx, width, height);
    }

    generateNoise(ctx, width, height);
    onGenerate && onGenerate(code);
  }, [code]);

  return <canvas onClick={handleClick} ref={canvasRef} width={100} height={40} />;
};

export default IdentifyingCode;
